package com.jhw.ymcc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jhw.ymcc.constants.BlacklistConstants;
import com.jhw.ymcc.domain.Smsblacklist;
import com.jhw.ymcc.exception.GlobalErrorCode;
import com.jhw.ymcc.mapper.SmsblacklistMapper;
import com.jhw.ymcc.service.ISmsblacklistService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jhw.ymcc.util.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jhw
 * @since 2022-09-24
 */
@Service
public class SmsblacklistServiceImpl extends ServiceImpl<SmsblacklistMapper, Smsblacklist> implements ISmsblacklistService {
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Override
    public boolean insert(Smsblacklist entity) {
        Wrapper<Smsblacklist> wrapper = new EntityWrapper<>();
        wrapper.eq("phone",entity.getPhone());
        Smsblacklist blacklist = selectOne(wrapper);
        AssertUtil.isNull(blacklist, GlobalErrorCode.DUPLICATE_ADDITION_ERROR);
        entity.setSendTime(new Date());
        return resetRedisBlacklist(super.insert(entity));
    }

    @Override
    public boolean updateById(Smsblacklist entity) {
        return resetRedisBlacklist(super.updateById(entity));
    }

    @Override
    public boolean deleteById(Serializable id) {
        return resetRedisBlacklist(super.deleteById(id));
    }

    /**
     * 重置redis中的黑名单
     * @param boo
     */
    private Boolean resetRedisBlacklist(boolean boo) {
        if (boo) {
            redisTemplate.delete(BlacklistConstants.BLACKLIST_REDIS_KEY);
        }
        return boo;
    }

    /**
     * 分页查询 @TODO
     * @param page
     * @return
     */
    @Override
    public Page<Smsblacklist> selectPage(Page<Smsblacklist> page) {
        Object obj = redisTemplate.opsForValue().get(BlacklistConstants.BLACKLIST_REDIS_KEY);
        if (obj == null) {
            List<Smsblacklist> blacklists = selectList(null);
            redisTemplate.opsForValue().set(BlacklistConstants.BLACKLIST_REDIS_KEY,blacklists);
            return super.selectPage(page);
        }
        Page<Smsblacklist> blacklistPage = new Page<>();
        List<Smsblacklist> blacklists = JSONArray.parseArray(JSON.toJSONString(obj), Smsblacklist.class);
        return blacklistPage.setRecords(blacklists);
    }
}
